from qturboframe.lib.utils.by import By
from qturboframe.lib.utils.__datatime_format__ import deal_datetime
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.lib.ranorex.exceptions import CsClientError
from qturboframe.public_ui.ucf_wpf.basecontrol import BaseControl
from qturboframe.public_ui.ucf_wpf.button import Button as UcfButton
from qturboframe.public_ui.ucf_wpf.context_menu import ContextMenu as UcfContextMenu


class DateTime(BaseControl):
    """
    日期控件对象

    :Attributes:
     - _driver: 控件所在的当前Control对象
     - _control: 控件元素Control对象
     - date_time: 当前的combobox对象
     - timeout: 步骤操作的超时时间

     :Raises
        CsClientError 没有找到控件异常

    :Example:
     - 例1: DateTime({By.XPATH:"/DateTime"})
     - 例2: DateTime({By.AUTOMATIONID:'automationid'})
     - 例3: DateTime(control)
     - 例4: DateTime({By.TEXT: 'Click'}, father=client)
     - 例5: DateTime({By.AUTOMATIONID:'automationid'}, father=client)
     - 例6: DateTime(control, father=client)
    """

    def __init__(self, element_para, father=None, timeout=10000):
        if isinstance(element_para, dict) and By.AUTOMATIONID in element_para:
            automation_id = element_para.get(By.AUTOMATIONID)
            xpath = ".//datetime[@automationid='{}']/container[@automationid='PART_Root']".format(automation_id)
            super().__init__({By.XPATH:xpath}, father, timeout)
        else:
            super().__init__(element_para, father, timeout)
        self.date_time = self._control

    def set_value(self, text):
        """
        选择日期

        :Args:
         - text: 日期，例如20210406

        :Raise:
         - None

        :Example:
         - 例1: date_time.set_value('20210406')
        """
        date_time_value_list = deal_datetime(text).split("/")
        if len(date_time_value_list)!=3:
            raise CsClientError(CustomError.Error_EQ03008001_Parameter_InCorrect,"数据:'{}'，格式不正确".format(text))

        year = date_time_value_list[0]
        month = date_time_value_list[1]
        day = date_time_value_list[2]

        self.date_time = self.__get_context_menu()

        self.select_year(year)
        self.select_month(month)
        self.select_day(day)

    def select_year(self, year):
        """
        选择年

        :Args:
         - year: 年，例如2021

        :Raise:
         - None

        :Example:
         - 例1: date_time.select_year('2021')
        """
        header_xpath = ".//button[@automationid='PART_HeaderButton']"
        previous_xpath = ".//button[@automationid='PART_PreviousButton']"
        next_xpath = ".//button[@automationid='PART_NextButton']"
        header_button = UcfButton({By.XPATH: header_xpath}, self.date_time, timeout=self.timeout)

        #切换到年的选择面板
        header_button.click()
        header_button.click()

        b_find = False
        while not b_find:
            header_button = UcfButton({By.XPATH: header_xpath}, self.date_time,timeout=self.timeout)
            previous_button = UcfButton({By.XPATH: previous_xpath}, self.date_time,timeout=self.timeout)
            next_button = UcfButton({By.XPATH: next_xpath}, self.date_time,timeout=self.timeout)
            header_button_text = header_button.get_text()
            header_year_list = header_button_text.split('-')
            min_year = int(header_year_list[0])
            max_year = int(header_year_list[1])
            year = int(year)

            if year < min_year:
                if previous_button.is_enabled():
                    previous_button.click()
                else:
                    raise CsClientError(CustomError.Error_EQ03008002_Parameter_Content_InCorrect,"'{}'已经是日历上显示的最小时间，但是要选择的时间为：{}，请输入正确的时间".format(min_year, year))
            elif year > max_year:
                if next_button.is_enabled():
                    next_button.click()
                else:
                    raise CsClientError(CustomError.Error_EQ03008002_Parameter_Content_InCorrect,"'{}'已经是日历上显示的最大时间，但是要选择的时间为：{}，请输入正确的时间".format(max_year, year))
            else:
                self.__select_value(".//container[@automationid='PART_YearView']", year)
                break

    def select_month(self, month):
        """
        选择月

        :Args:
         - month: 年，例如12

        :Raise:
         - None

        :Example:
         - 例1: date_time.select_month('12')
        """
        xpath = ".//container[@automationid='PART_YearView']"
        self.__select_value(xpath, str(int(month))+"月")

    def select_day(self, day):
        """
        选择日

        :Args:
         - day: 年，例如12

        :Raise:
         - None

        :Example:
         - 例1: date_time.select_day('12')
        """
        xpath = ".//container[@automationid='PART_MonthView']"
        self.__select_value(xpath, str(int(day)))

    def __get_context_menu(self):
        """
        得到日历的上选文对象中的datetime
        :return:
        """
        UcfButton({By.XPATH: ".//button"}, self.date_time, timeout=self.timeout).click()
        context_menu = UcfContextMenu()
        xpath = ".//datetime//datetime//container[@automationid='PART_Root']"
        date_time = context_menu.context_menu.find_element_by_attribute(By.XPATH, xpath, timeout=self.timeout)
        return date_time

    def __select_value(self, xpath, value):
        view_container = self.date_time.find_element_by_attribute(By.XPATH, xpath, timeout=self.timeout)
        xpath = ".//button[@text='{}' and @visible='true']".format(value)
        button = UcfButton({By.XPATH: xpath}, view_container, timeout=self.timeout)
        button.click()

